package com.parking.carsystem.parkingchargesystem.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.CardView;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.module.AbsenceData;
import com.parking.carsystem.parkingchargesystem.module.GroupListModule;
import com.parking.carsystem.parkingchargesystem.module.ParkingPlateGroupModule;
import com.parking.carsystem.parkingchargesystem.utils.SPUtils;
import com.parking.carsystem.parkingchargesystem.view.BottomDialog;
import com.parking.carsystem.parkingchargesystem.view.LicensePlateView;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import ttyy.com.recyclerexts.base.EXTRecyclerAdapter;
import ttyy.com.recyclerexts.base.EXTViewHolder;

public class LicensePlateAddActivity extends BaseActivity implements LicensePlateView.InputListener, View.OnClickListener, BottomDialog.ChooseTextLisenter {
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.text)
    TextView text;
    @BindView(R.id.remind_input_plate)
    TextView remindInputPlate;
    @BindView(R.id.activity_lpv)
    LicensePlateView activityLpv;
    @BindView(R.id.group_list)
    RecyclerView groupList;
    @BindView(R.id.update_group)
    TextView updateGroup;
    @BindView(R.id.hisrory_parking_text)
    TextView hisroryParkingText;
    @BindView(R.id.hisrory_parking_data)
    RecyclerView hisroryParkingData;
    @BindView(R.id.delete_history)
    ImageView deleteHistory;
    @BindView(R.id.add_paking)
    TextView addPaking;
    @BindView(R.id.main_rl_container)
    RelativeLayout mainRlContainer;
    @BindView(R.id.blue_parking_style)
    TextView blueParkingStyle;
    @BindView(R.id.yellow_parking_style)
    TextView yellowParkingStyle;
    @BindView(R.id.other_parking_style)
    TextView otherParkingStyle;
    @BindView(R.id.plate_style)
    LinearLayout plateStyle;
    @BindView(R.id.delete_group)
    TextView deleteGroup;
    @BindView(R.id.add_group)
    TextView addGroup;
    @BindView(R.id.update_group_msg)
    RelativeLayout updateGroupMsg;
    private EXTRecyclerAdapter<String> recyclerAdapter;
    private String content;
    private EXTRecyclerAdapter<GroupListModule.DataBean> groupRecyclerAdapter;
    private ArrayList<GroupListModule.DataBean> beanList;

    private int colorType = -1;
    private GroupListModule.DataBean dataBean;
    private GroupListModule.DataBean tempDataBean;
    private String monthlySubscription;
    private String parkingHistoryList;
    private String[] split;
    ArrayList<String> historyList = new ArrayList<>();
    private BottomDialog bottomDialogPay;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_lisense_plate_add;
    }

    @Override
    public void initView() {
        activityLpv.setInputListener(this);
        deleteHistory.setOnClickListener(this);
        back.setOnClickListener(this);
        addPaking.setOnClickListener(this);
        addGroup.setOnClickListener(this);
        deleteGroup.setOnClickListener(this);
        updateGroup.setOnClickListener(this);
        blueParkingStyle.setOnClickListener(this);
        yellowParkingStyle.setOnClickListener(this);
        otherParkingStyle.setOnClickListener(this);
        back.setVisibility(View.VISIBLE);
        text.setText("添加车牌");
        activityLpv.setKeyboardContainerLayout(mainRlContainer);
        activityLpv.showLastView();
        activityLpv.hideLastView();
        activityLpv.onSetTextColor(R.color.colorAccent);
        monthlySubscription = getIntent().getStringExtra(Constant.MONTHLYSUBSCRIPTION);
        historyList.clear();
        parkingHistoryList = SPUtils.getInstance(this).getString(Constant.PARKINGADDHISTORY);
        if (!TextUtils.isEmpty(parkingHistoryList)) {
            split = parkingHistoryList.split("@");
            for (String s : split) {
                historyList.add(s);
            }
        }
        bottomDialogPay = new BottomDialog(0, this, 2);
        bottomDialogPay.setChooseTextLisenter(this);
    }

    @Override
    public void initData() {
        getGroupList();
        //分组
        groupList.setLayoutManager(new LinearLayoutManager(this));
        groupRecyclerAdapter = new EXTRecyclerAdapter<GroupListModule.DataBean>(R.layout.item_parking_plate_list) {
            @Override
            public void onBindViewHolder(EXTViewHolder extViewHolder, int i, final GroupListModule.DataBean module) {
                ImageView image = extViewHolder.findViewById(R.id.image);
                ImageView edit = extViewHolder.findViewById(R.id.edit);
                ImageView delete = extViewHolder.findViewById(R.id.delete);
                TextView parking_name = extViewHolder.findViewById(R.id.parking_name);
                TextView parking_count = extViewHolder.findViewById(R.id.parking_count);
                if (module.chooseStatus) {
                    image.setImageResource(R.mipmap.selected);
                } else {
                    image.setImageResource(R.mipmap.unselected);
                }
                parking_name.setText(module.groupName);
                parking_count.setText(module.vehicles.size() + "辆车");
                image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!module.chooseStatus) {
                            if (dataBean != null) {
                                dataBean.chooseStatus = false;
                            }
                            module.chooseStatus = true;
                            dataBean = module;
                        }
                        groupRecyclerAdapter.notifyDataSetChanged();
                    }
                });
                edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tempDataBean = module;
                        bottomDialogPay.setTitle("修改分组");
                        bottomDialogPay.show();
                    }
                });
                delete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        beanList.remove(module);
                        groupRecyclerAdapter.notifyDataSetChanged();
                        deleteGroup(module.id);
                    }
                });
            }
        };
        groupRecyclerAdapter.setDatas(beanList);
        groupList.setAdapter(groupRecyclerAdapter);
        //历史记录
        hisroryParkingData.setLayoutManager(new GridLayoutManager(this, 3));
        recyclerAdapter = new EXTRecyclerAdapter<String>(R.layout.item_history_plate) {
            @Override
            public void onBindViewHolder(EXTViewHolder extViewHolder, int i, String s) {
                extViewHolder.setText(R.id.parking_name, s);
            }
        };
        recyclerAdapter.setDatas(historyList);
        hisroryParkingData.setAdapter(recyclerAdapter);
    }

    /**
     * 获取分组列表
     */
    private void getGroupList() {
        showLoading();
        OkGo.<String>get(Constant.url + Constant.GROUP_LIST_DATA)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
                        Gson gson = new Gson();
                        GroupListModule groupListModule = gson.fromJson(response.body(), GroupListModule.class);
                        if (groupListModule.code == 200) {
                            beanList = (ArrayList<GroupListModule.DataBean>) groupListModule.data;
                            groupRecyclerAdapter.setDatas(beanList);
                            groupRecyclerAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                    }
                });
    }

    @Override
    public void inputComplete(String content) {
        //获取到输入框的内容
        showToast(content);
        this.content = content;
    }

    @Override
    public void deleteContent() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.delete_history:
                historyList.clear();
                SPUtils.getInstance(this).put(Constant.PARKINGADDHISTORY, "");
                recyclerAdapter.setDatas(null);
                recyclerAdapter.notifyDataSetChanged();
                break;
            case R.id.back:
                exitFinish();
                break;
            case R.id.add_paking:
                if (!TextUtils.isEmpty(content) && colorType != -1 && dataBean != null && !TextUtils.isEmpty(dataBean.id)) {
                    historyList.add(content);
                    recyclerAdapter.notifyDataSetChanged();
                    saveParkingPlate(content);
                    addParkingPlate();
                } else {
                    showToast("请填写车牌或者选择车牌颜色或分组");
                }
                break;
            case R.id.add_group:
                bottomDialogPay.setTitle("添加分组");
                bottomDialogPay.show();
//                Intent intent = new Intent(this, AddParkingPlateActivity.class);
//                startActivityForResult(intent, 0);
                break;
            case R.id.delete_group:
                //删除分组
                Intent intent1 = new Intent(this, UpdateOrDeleteGroupActivity.class);
                intent1.putExtra(Constant.TITLE, "删除分组");
                intent1.putParcelableArrayListExtra(Constant.GROUP_LIST, beanList);
                startActivityForResult(intent1, 0);
                break;
            case R.id.update_group:
                //修改分组名字
                Intent intent2 = new Intent(this, UpdateOrDeleteGroupActivity.class);
                intent2.putExtra(Constant.TITLE, "编辑分组");
                intent2.putParcelableArrayListExtra(Constant.GROUP_LIST, beanList);
                startActivityForResult(intent2, 0);
                break;
            case R.id.blue_parking_style:
                colorType = 0;
                blueParkingStyle.setBackgroundResource(R.drawable.parking_choose_blue);
                yellowParkingStyle.setBackgroundResource(R.drawable.parking_choose_radue_gray);
                otherParkingStyle.setBackgroundResource(R.drawable.parking_choose_right_radue_gray);
                blueParkingStyle.setTextColor(getResources().getColor(R.color.white));
                yellowParkingStyle.setTextColor(getResources().getColor(R.color.diff_text_color));
                otherParkingStyle.setTextColor(getResources().getColor(R.color.diff_text_color));
                break;
            case R.id.yellow_parking_style:
                colorType = 1;
                blueParkingStyle.setBackgroundResource(R.drawable.parking_choose_gray);
                yellowParkingStyle.setBackgroundResource(R.drawable.parking_choose_radue_blue);
                otherParkingStyle.setBackgroundResource(R.drawable.parking_choose_right_radue_gray);
                blueParkingStyle.setTextColor(getResources().getColor(R.color.diff_text_color));
                yellowParkingStyle.setTextColor(getResources().getColor(R.color.white));
                otherParkingStyle.setTextColor(getResources().getColor(R.color.diff_text_color));
                break;
            case R.id.other_parking_style:
                colorType = 2;
                blueParkingStyle.setBackgroundResource(R.drawable.parking_choose_gray);
                yellowParkingStyle.setBackgroundResource(R.drawable.parking_choose_radue_gray);
                otherParkingStyle.setBackgroundResource(R.drawable.parking_choose_right_radue_blue);
                blueParkingStyle.setTextColor(getResources().getColor(R.color.diff_text_color));
                yellowParkingStyle.setTextColor(getResources().getColor(R.color.diff_text_color));
                otherParkingStyle.setTextColor(getResources().getColor(R.color.white));
                break;
        }
    }

    private void exitFinish() {
        if (!TextUtils.isEmpty(monthlySubscription)) {
            //优惠券的添加车牌界面
            Intent intent = new Intent();
            intent.putExtra(Constant.MONTHLYSUBSCRIPTION_NAME, content);
            setResult(Constant.MONTHLYSUBSCRIPTIONPARKING, intent);
        } else {
            setResult(Constant.ADDPARKINGRESULTCODE);
        }
        finish();
    }

    /**
     * 添加车牌
     */
    private void addParkingPlate() {
        showLoading();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("plateColor", String.valueOf(colorType));
        hashMap.put("plateNumber", content);
        JSONObject jsonObject = new JSONObject(hashMap);
        OkGo.<String>post(Constant.url + Constant.ADDVEHICLE + dataBean.id)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        stopLoading();
                        try {
                            JSONObject jsonObject1 = new JSONObject(response.body());
                            int code = jsonObject1.getInt("code");
                            String msg = jsonObject1.getString("msg");
                            if (code == 200) {
                                exitFinish();
                            } else {
                                showToast(msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        stopLoading();
                    }
                });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (activityLpv.getKeyDownVisible()) {
                activityLpv.hildeKeyDown();
            } else {
                exitFinish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Constant.ADDPARKINGGROUPRESULTCODE) {
            getGroupList();
        }
    }

    private void saveParkingPlate(String parkingName) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < historyList.size(); i++) {
            builder.append(historyList.get(i));
            if (i != historyList.size() - 1) {
                builder.append("@");
            }
        }
        SPUtils.getInstance(this).put(Constant.PARKINGADDHISTORY, builder.toString());
    }

    /**
     * 删除分组
     *
     * @param ids 分组id 6170941768e7403f81e909c0b5a2a578,138a4ade72424ee9afe78322257ee8ec,e7a4428634114699b1e910f601ee924e
     */
    private void deleteGroup(String ids) {
        OkGo.<String>delete(Constant.url + Constant.DELETEGROUPSREMOVE + ids)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        parseJson(response.body());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        showToast(response.message());
                    }
                });
    }

    @Override
    public void chooseText(AbsenceData text) {
        if (tempDataBean != null) {
            updateGroup(text.text);
        } else {
            addParkingPlate(text.text);
        }
    }

    private void updateGroup(final String newGroupName) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("id", tempDataBean.id);
        hashMap.put("groupName", newGroupName);
        JSONObject jsonObject = new JSONObject(hashMap);
        OkGo.<String>post(Constant.url + Constant.GROUPEDIT)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject jsonObject1 = new JSONObject(response.body());
                            int code = jsonObject1.getInt("code");
                            String msg = jsonObject1.getString("msg");
                            if (code == 200) {
                                tempDataBean.groupName = newGroupName;
                                groupRecyclerAdapter.notifyDataSetChanged();
                                tempDataBean = null;
                            } else {
                                showToast(msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        showToast(response.message());
                    }
                });
    }

    /**
     * 添加车牌分组
     *
     * @param groupName
     */
    private void addParkingPlate(final String groupName) {
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("groupName", groupName);
        JSONObject jsonObject = new JSONObject(hashMap);
        OkGo.<String>post(Constant.url + Constant.GROUPADD)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            JSONObject jsonObject1 = new JSONObject(response.body());
                            int code = jsonObject1.getInt("code");
                            String msg = jsonObject1.getString("msg");
                            if (code == 200) {
                                getGroupList();
                            } else {
                                showToast(msg);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        showToast(response.message());
                    }
                });
    }
}
